<template>
  <div class="index overauto flex justify-center  bg-[#F6F7FB]"
       style="width: 100vw; height: 100vh; overflow-x: hidden;" v-if="!isPlaceAnOrder && !showSuccess && !showOrder">
    <div class="content" >
      <div class="relative swiper">
        <el-carousel :autoplay="true">
          <el-carousel-item   v-for="(item,index) in product.picture?.split(',')"
                              :key="index"
          >
            <div class="swiper-item bg"
                 :style="`background-image: url(${ item })`">

            </div>
          </el-carousel-item>
        </el-carousel>
        <SwiperBuyInfo :list="rollList" :product="product" v-if="rollList?.style=='1'"/>
      </div>
      <div class="px-[18PX] mt-[14PX] pb-[100PX] pricebox">
          <div class="py-[6PX] px-[15PX] flex justify-between cont">
            <div class="left" :class="!product.discountedPrice && product.countdown?'pb-[15PX]':''">
              <div class="flex items-center">
                <div class="flex items-baseline mr-[8PX]">
                  <div class="text-[#fff] text-[14PX] mr-[4PX] font-semibold">{{ areaInfo.currencySymbol }}</div>
                  <div class="text-[#fff] font-bold pb-[5PX] text-[24PX]">{{ product.discountedPrice || product.originalPrice }}</div>
                </div>

                <div class="w-[74PX] h-[22PX] flex justify-center items-center text-[14PX] text-[#FF3400] font-semibold disbg" v-if="product.discountedPrice"> {{ (((product.originalPrice - product.discountedPrice)  / product.originalPrice) * 100).toFixed(0) }}%OFF</div>
              </div>
              <div class="text-[12PX] relative top-[-4PX] line-through" style="color: rgba(255,255,255,.5);" v-if="product.discountedPrice">
                {{ areaInfo.currencySymbol }}{{ product.originalPrice || 0 }}
              </div>

            </div>
            <div class=" right">
              <div class="text-right text-[#fff] text-[16PX]"> {{getLanguage(props.product.language).limitTimeBuy}}</div>
              <div style="gap: 3PX" class="flex mt-[3PX] items-center time" v-if="product.countdown">
                <!-- <div class="text-[12PX] text-[#fff]">距結束1天</div> -->
                <div class="cycle flex-center text-[12PX] text-[#FF3400]">
                  {{ custDown?.hours.toString().padStart(2, '0') }}
                </div>

                <div class=" text-[#fff]">
                  :
                </div>

                <div class="cycle  flex-center text-[12PX] text-[#FF3400]">
                  {{ custDown?.minutes.toString().padStart(2, '0') }}
                </div>

                <div class=" text-[#fff]">
                  :
                </div>

                <div class="cycle  flex-center text-[12PX] text-[#FF3400]">
                  {{ custDown?.seconds.toString().padStart(2, '0') }}
                </div>

              </div>
            </div>
          </div>
          <div class="pt-[10PX] pb-[15PX] px-[16PX] relative top-[-6PX] rounded-[12PX] bg-[#fff] infobox">
            <div class="coupon bg flex items-center justify-between rounded-[6PX] overflow-hidden pl-[12PX] py-[6PX]" v-if="product.couponAmount">
              <div class="flex items-center">
                <div class="text-[#fff] rounded-[3PX] text-[12PX] px-[4PX] py-[2PX] mr-[8PX]" style="background: linear-gradient( 136deg, #FD3281 0%, #FC5F46 100%);"> {{getLanguage(props.product.language).anyCoupon}} </div>
                <div class="text-[#FD2D55] text-[12PX] font-medium">{{getLanguage(props.product.language).instantDiscount}}{{areaInfo.currencySymbol}}{{ product.couponAmount }}</div>
              </div>

              <div class=" py-[6PX] text-[14PX] text-[#FD2D55] cursor-pointer"
              :class="screenWidth>426?'px-[18PX]':'px-[12PX]'"
                 @click="handleBtnClick({ type:'pickupCoupon' })">
                {{ isPickup ? getLanguage(props.product.language).received : getLanguage(props.product.language).unclaimed }}
              </div>

            </div>
            <div class="top-title text-[#333] text-[16PX] font-semibold mt-[15PX] ">
              {{ product.titleExternal }}
            </div>
            <div class="subTitle text-[#999999] text-[16PX] mt-[8PX] px-[0px]">
              {{ product.subtitle }}
            </div>
            <div class="lint my-[12PX]" style="border-top: dashed 1PX #f5f5f5"> </div>
            <div class="flex items-center tagbox" v-if="product.tagValue">
              <div class="flex tags" v-for="(item,index) in product.tagValue?.split(',')" :key="index">
                <div class="flex items-end tag">
                    
                    <img
                      src="../../../../assets/template/template4/img05.png"
                      class="w-[14PX] h-[14PX] mr-[4PX]"
                      v-if="index === 1"
                    />
                    <img
                      src="../../../../assets/template/template4/img06.png"
                      class="w-[14PX] h-[14PX] mr-[4PX]"
                       v-else-if="index === 2"
                    />
                    <img
                      src="../../../../assets/template/template4/img04.png"
                      class="w-[14PX] h-[14PX] mr-[4PX]"
                      v-else
                    />
                    <div class="text-[12PX] text-[#999999]">{{ item }}</div>
                </div>
                <div class="text-[#EBEBEB] mx-[4PX] text-[12PX] line" v-if="index<product.tagValue?.split(',').length-1">/</div>
              </div>
              
              <!-- <div class="text-[#EBEBEB] mx-[4PX] line">/</div>
              <div class="flex items-end tag">
                  <img
                    src="../../../../assets/template/template4/img05.png"
                    class="w-[14PX] h-[14PX] mr-[4PX]"
                  />
                  <div class="text-[12PX] text-[#999999]">{{getLanguage(props.product.language).freeShipping}}</div>
              </div>
              <div class="text-[#EBEBEB] mx-[4PX] line">/</div>
              <div class="flex items-end tag">
                  <img
                    src="../../../../assets/template/template4/img06.png"
                    class="w-[14PX] h-[14PX] mr-[4PX]"
                  />
                  <div class="text-[12PX] text-[#999999]">{{getLanguage(props.product.language).appreciationPeriod}}</div>
              </div> -->
            </div>
          </div>
          <!-- 商品評價 -->
          <div class="mt-[6PX] px-[16PX] py-[14PX] bg-[#fff] rounded-[12PX]">
            <div class="empty" v-if="!hasComment">
              {{getLanguage(props.product.language).noComment}}
            </div>
            <!-- 有評價時引入評價組件 -->
             <Evaluation  v-else  :comment-list="commentList" :comment-avg-score="commentAvgScore" :product="product"/>
          </div>
          <!-- 商品詳情 -->
          <div class="mt-[12PX] px-[16PX] py-[14PX] bg-[#fff] rounded-[12PX]">
            <div class="tit">{{getLanguage(props.product.language).productDescription}}</div>
            <div class="mt-[10PX] htmlDetails" ref="content" v-html="product.detail"></div>
          </div>

        <div class="mt-[15PX]">
          <Recommend :recommend-list="recommendList"
                     v-if="recommendList && recommendList.length>0"/>
        </div>

          <div class="mt-[6PX] px-[16PX] py-[14PX] bg-[#fff] rounded-[12PX]"  v-if="policyList && policyList.length>0">
            <div class=" mt-[20PX] pb-[20PX]">
            <el-collapse v-model="activeNames"
                        v-if="policyList && policyList.length>0">
              <el-collapse-item :title="item.title" :name="item.id" v-for="(item,index) in policyList.filter(policy=>policy.type==3)"
                                :key="index">
                <div v-html="item.detail"></div>
              </el-collapse-item>

            </el-collapse>
            </div>
          </div>

          

        </div>



    </div>

    <div class="w-full max-w-[640PX] mx-auto fixed flex items-center justify-between px-[15PX] py-[15PX] bg-[#fff] bottom-0 left-[50%] btnbox z-10" style="transform: translateX(-50%);">
      <!-- <div class="flex flex-col items-center justify-center cursor-pointer left" @click="toKefu">
        <img
          src="../../../../assets/template/template4/phone.png"
          class="w-[20PX] h-[20PX]"
        />
        <div class="text-[#333] font-medium" >Line</div>
      </div> -->
      <div class="flex right" style="width:100%">
        <!-- <div class="w-[30%] h-[45PX]  flex justify-center items-center mr-[10PX] rounded-[3PX] btnbox" style="border:1PX solid #e4e4e4;">訂單</div> -->
        <div class="w-[100%] h-[45PX] cursor-pointer ml-auto flex justify-center  items-center bg-[#FF3400] text-[#fff] rounded-[3PX] btnbox" style="border:1PX solid #FFA200;box-shadow: inset 0 2PX 5PX 1PX #FF8800;"  @click="goToBuy">
          <img
            class="w-[14PX] h-[14PX] mr-[5PX]"
            src="../../../../assets/template/template2/shoppingCar.png"
            alt=""
          />
          {{getLanguage(props.product.language).buyNow}}
        </div>
      </div>
    </div>


  </div>
  <PlaceAnOrder ref="placeAnOrderRef" :isPlaceAnOrder="isPlaceAnOrder && !showSuccess && !showOrder" @update:isPlaceAnOrder="updatePlaceAnOrder"
    :product="product"
    :sku-info="skuInfo"
    :hasProvince="hasProvince"
    @execute="handleBtnClick"
    :original-sku="originalSku"
    :areaInfo="areaInfo"
    :provinceList="provinceList"
    :logisticsList="logisticsList"
    :storeList="storeList"
    :globalConfig="globalConfig"
    :isPickup="isPickup"
    :remoteList="remoteList"
    :policy-list="policyList"
    :instruction="instruction"
  />
  <SuccessPage v-if="showSuccess && !showOrder" @update:showSuccess="updateShowSuccess" :orderInfo="orderInfo" :product="product" :policyList="policyList" :isRemote="isRemote"/>
  <OrderPage v-if="showOrder" @update:showOrder="updateShowOrder" :orderInfo="orderInfo" :product="product"/>

</template>
<script lang="ts" setup>

import {useMessage} from "@/hooks/web/useMessage";
import Evaluation from "../components/evaluation.vue";
import PlaceAnOrder from "./placeAnOrder.vue";
import { getLanguage } from "@/utils/langue";
import SuccessPage from "../components/success.vue";
import SwiperBuyInfo from "../components/swiperBuyInfo.vue";
import OrderPage from "@/views/Product/template/components/order.vue";
import Recommend from "@/views/Product/template/components/Recommend.vue";




const message = useMessage();
const props = defineProps({
  recommendList: {
    type: Array,
    required: false,
    default: () => []
  },
  product: {
    type: Object,
    required: false,
    default: () => {
    }
  },
  areaInfo: {
    type: Object,
    required: false,
    default: () => {
    }
  },
  skuInfo: {
    type: Array,
    required: false,
    default: () => []
  },
  hasProvince:{
    type: Boolean,
    default:true,
  },
  //原商品列表sku
  originalSku: {
    type: Array,
    required: false,
    default: () => []
  },
  provinceList: {
    type: Array,
    required: false,
    default: () => []
  },
  logisticsList: {
    type: Array,
    required: false,
    default: () => []
  },
  storeList: {
    type: Array,
    required: false,
    default: () => []
  },
  globalConfig:{
    type: Object,
    required: false,
    default: () => {}
  },
  custDown:{
    type:Object,
    defaulst:() => {}
  },
  commentList: {
    type: Array,
    required: false,
    default: () => []
  },
  commentAvgScore: {
     type: Number,
    required: false,
    default: 0
  },
  remoteList:{
    //偏远地区列表
    type: Array,
    default: () => []
  },
  showSuccess:{
    type: Boolean,
    default: false
  },
  orderInfo:{
    type: Object,
    default: () => {}
  },
  policyList: {
    type: Array,
    required: false,
    default: () => []
  },
  instruction: {
    type: Object,
    required: false,
    default: () => {}
  },
  rollList:{
    type: Object,
    required: false,
    default: () => {}
  },
  showOrder:{
    type: Boolean,
    default: false
  }
});

const isRemote = ref(false)

const screenWidth = ref(window.innerWidth)

const formRef = ref(null)

const placeAnOrderRef = ref(null)
const isPlaceAnOrder = ref(false)
const activeNames = ref([''])

const emit = defineEmits(['confirm', 'execute']);

const hasComment = ref(props.commentList.length > 0 || false)

const isPickup = ref(false)

const config = ref([
  {
    name: "免运费",
  },
  {
    name: "货到付款",
  },
  {
    name: "15天鉴赏期",
  },
  {
    name: "正品保证",
  }
])


const skuList = ref([])

const initConfig = [
  {
    name: "姓名",
    code: "customerName",
    xs: 24,
    xl: 24,
    required: true,
    show:true,
  },
  {
    name: "手机",
    code: "customerPhone",
    xs: 24,
    xl: 24,
    required: true,
    show:true,
  },
  {
    name: "一級區域",
    code: "areaName",
    type: "select",
    label: "name",
    value: "name",
    xs: 24,
    xl: 8,
    required: true,
    show:true,
  },
  {
    name: "二級區域",
    code: "cityName",
    type: "select",
    label: "name",
    value: "name",
    xs: 24,
    xl: 8,
    required: true,
    show:true,
  },
  // {
  //   name: "选择地区",
  //   code: "regionName",
  //   type: "select",
  //   label: "name",
  //   value: "id",
  //   xs: 24,
  //   xl: 8,
  //   required: true
  // },
  {
    name: "选择门店",
    code: "addressId",
    type: "select",
    label: "name",
    value: "id",
    xs: 24,
    xl: 24,
    required: false,
    directly: true,
    show:true,
  },
  {
    name: "详细地址",
    code: "detailAddress",
    xs: 24,
    xl: 24,
    required: true,
    show:true,
  },
  {
    name: "留言",
    code: "message",
    type: "textarea",
    xs: 24,
    xl: 24,
    required: false,
    show:true,
  }
]

const inputConfig = ref([...initConfig]);

const updateShowOrder = (val) => {
  //关闭成功页面
  emit('execute', {
    type: 'closeOrder',
  })
}

const computePrice = computed(() => {
  //获取sku列表
  //查看是否全部选中
  let isAllSelected = isAllPropertySelected().isAllSelected

  if (isAllSelected) {

    let selectedItem = isAllPropertySelected().selectedItem

    let discountPrice = (selectedItem.discountedPrice || 0) * form.value.number;
    if (isPickup.value) {
      discountPrice -= (props.product.couponAmount || 0)
    }
    return {
      price: ((selectedItem.price || 0) * form.value.number).toFixed(2),
      discountPrice: discountPrice.toFixed(2),
      lessPrice: (selectedItem.originalPrice || 0) * form.value.number - (selectedItem.discountedPrice || 0) * form.value.number
    }

  } else {
    //原价为商品价格

    let discountPrice = (props.product.discountedPrice || 0) * form.value.number;
    if (isPickup.value) {
      discountPrice -= (props.product.couponAmount || 0)
    }

    return {
      price: ((props.product.originalPrice || 0) * form.value.number).toFixed(2),
      discountPrice: discountPrice.toFixed(2),
      lessPrice: (props.product.originalPrice || 0) * form.value.number - (props.product.discountedPrice || 0) * form.value.number
    }
  }
})

/**
 * 计算rules
 * */
const rules = computed(() => {

  let obj = {}
  inputConfig.value.forEach(item => {
    if (item.required) {
      obj[item.code] = [{
        required: true,
        message: `请${item.type == 'select' ? '选择' : '输入'}${item.name}`,
        trigger: `${item.type == 'select' ? 'change' : 'blur'}`
      }]
    }

  })

  console.log(obj, "===")
  return obj
})

let initForm = {
  number: 1,
  activeLogistics: 0
}

const form = ref({
  ...initForm
})

const handleBtnClick = (e) => {
  let type = e.type;
  try {
    fn[type](e)
  } catch (e) {
    console.log(`${type}不存在`)
  }
}

const isAllPropertySelected = () => {
  let isAllSelected = true;
  let selectedItem = {}

  if (skuList.value.length > 0) {
    for (let i = 0; i < skuList.value.length; i++) {
      let item = skuList.value[i]
      if (!item.selected) {
        isAllSelected = false;
        break;
      }
    }

    if (isAllSelected) {
      //获取选中的sku
      let str = skuList.value.map(item => {
        //获取选中的list
        let list = item.list;
        let it = list[item.selected - 1]
        return it.name
      }).join('§');

      selectedItem = props.originalSku.find(at => {
        return at.propertyValue == str
      })

    }

  }


  return {
    selectedItem,
    isAllSelected
  }
}

const fn = {
  confirm(data){
    isRemote.value = data.isRemote
    emit('execute', data)
  },
  store(data){
    emit('execute', data)
  },
  pickupCoupon() {
    if (!isPickup.value) {
      isPickup.value = true;
      message.success(getLanguage(props.product.language).pickupSuccess)
    }
  },
  async submit() {
    try {
      let res = await formRef.value.validate();

      let item = inputConfig.value.find(item => {
        return item.code == 'regionName'
      })

      //查看有没有v选择sku
      if (isAllPropertySelected().isAllSelected) {

        let addressItem = inputConfig.value.find(at=>{
          return at.code == "addressId"
        })


        let address = null;
        if(addressItem){
          let lis = addressItem.list;

          console.log(lis,"==============")

          if(form.value.addressId){
            address = lis.find(at=>{
              return at.id == form.value.addressId
            })?.name
          }
        }


        emit('execute', {
          type: 'confirm',
          form: form.value,
          address:address,
          skuList: skuList.value,
          priceInfo: computePrice.value,
          isPickup: isPickup.value,
          regionList: item.list,
          regionName1: item.list.find(at => at.id == form.value.regionName)?.name,
          selectedProperty: isAllPropertySelected().selectedItem,
          thaliId: product.value.thaliFlag == 1 ?   product.value.thalis[activeModel.value]?.id : '',
          success() {
            if(props.globalConfig.orderDelectSteat == 1){
              form.value = {
                ...initForm
              }
            }

          }
          //其他 sku等信息
        })
      } else {
        message.error("请选择sku2");
      }


    } catch (e) {
      console.log(e)
      for (let i in e) {
        message.error(e[i][0].message);
        return
      }
    }
  },
  logistics({index}) {
    form.value.activeLogistics = index;
  },
  sku({item, it, index, idx}) {
    item.selected = idx + 1;
  }
}

const onChange = code => {
  if (code == 'areaName') {
    form.value.cityName = ''
    form.value.regionName = ''
    //生成
    let item = inputConfig.value.find(at => {
      return at.code == 'cityName'
    })
    //获取市
    let it = props.provinceList.find(at => {
      return at.name == form.value[code];
    })

    item.list = it.list || [];


    item = inputConfig.value.find(at => {
      return at.code == 'regionName'
    })

    item.list = []

    item = inputConfig.value.find(at => {
      return at.code == 'addressId'
    })

    item.list = [];

  } else if (code == 'cityName') {
    form.value.regionName = ''

    let item = inputConfig.value.find(at => {
      return at.code == 'regionName'
    })

    let item1 = inputConfig.value.find(at => {
      return at.code == 'cityName'
    })

    let it = item1.list.find(at => {
      return at.name == form.value.cityName
    })

    item.list = it.list


    item = inputConfig.value.find(at => {
      return at.code == 'addressId'
    })
    item.list = [];
  } else if (code == 'regionName') {


  } else if (code == 'addressId') {
    let it = props.storeList.find(at => {
      return at.id == form.value[code]
    })

    form.value.detailAddress = it.detailedAddress
  }
}


watch(() => props.provinceList, () => {
  let item = inputConfig.value.find(at => {
    return at.code == 'areaName'
  })
  item.list = props.provinceList
}, {
  deep: true,
  immediate: true
})

watch(() => [form.value.activeLogistics, form.value.regionName], () => {
  if (form.value.regionName) {
    if (props.logisticsList[form.value.activeLogistics]?.directlyStatus == 0) {
      //获取store
      emit('execute', {
        type: 'store',
        data: form.value,
        callback(storeList) {
          let item = inputConfig.value.find(at => {
            return at.code == 'addressId'
          })
          item.list = storeList.map(item => {
            return {
              id:item.id,
              name: item.storeName,
              address: item.detailedAddress
            }
          })
        }
      })
    }

  }
}, {
  deep: true,
  immediate: true
})


watch(() => props.skuInfo, () => {
  skuList.value = props.skuInfo;
  console.log(props.skuInfo, "props.skuInfo")

  console.log(skuList.value, "skuList.valueskuList.valueskuList.value")
}, {
  deep: true,
  immediate: true
})

const toKefu = () => {
  if(props.product?.lineContact){
    window.open(props.product?.lineContact)
  }
}

/**
 * 跳轉購買
*/
const goToBuy = () => {
  isPlaceAnOrder.value = true;
  // placeAnOrderRef.value.show()
  // 关闭当前页面样式
}

const updatePlaceAnOrder = (val) => {
  isPlaceAnOrder.value = val;
}

const updateShowSuccess = (val) => {
  // showSuccess.value = val;
  isPlaceAnOrder.value = false;
  //关闭成功页面
  emit('execute', {
      type: 'closeSuccess',
    })
}

const handleResize = () => {
  screenWidth.value = window.innerWidth;
};

onMounted(() => {
  window.addEventListener('resize', handleResize);
});

// 在组件卸载时移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});



</script>
<style scoped lang="less">
@import "@/common";

.index {
  .content {
    width: 640PX;
    height: 100%;

    .top-title {
      font-size: 14PX !important;

      .bar {
        width: 4PX;
      }
    }

    .subTitle {
      font-size: 14PX !important;
    }

    .swiper {
      width: 100%;
      height: 640PX;

      .swiper-item {
        width: 100%;
        height: 640PX;
      }

      .benefit {
        width: 100%;
        height: 64PX;

        .qianggou-num {
          padding: 5PX 12PX;
        }
      }


    }
    .cycle {
        width: 18PX;
        height: 18PX;
        border-radius: 4PX;
        background: #FFE5D6;
      }

    .price {
      font-size: 28PX;
      margin-bottom: -5PX;
    }

    .coupon {
      width: 100%;
      // height: 45PX;
      background-image: url("@/assets/template/template4/img01.png") ;
      background-repeat: no-repeat;
      background-position: 88.2% 100%;
      background-size: auto 100%;
    }


    .icons {
      width: 14PX;
      height: 14PX;
    }
  }

  .ft12 {
    font-size: 12PX !important;
  }
}

.pricebox{
  .cont{
    background: url("@/assets/template/template4/img02.png") no-repeat center center;
    background-size: 100% 100%;
    border-radius: 12PX 12PX 0 0;
    .left{
      .disbg{
        background: url('@/assets/template/template4/img03.png') no-repeat center center;
        background-size: 100% 100%;
      }
    }

  }
}


@media screen and (max-width: 640PX) {
  .index {
    .content {
      width: 100%;

      .swiper {
        width: 100vw;
        height: 100vw;

        .swiper-item {
          width: 100vw;
          height: 100vw;
        }
      }
    }

    .ft12 {
      .font(18);
    }

  }
}

:deep(.el-carousel) {
  width: 100%;
  height: 100%;

  .el-carousel__container {
    width: 100%;
    height: 100%;
  }
}

:deep(.el-input-number) {
  width: 135PX;
  height: 30PX;

  .el-input-number__decrease, .el-input-number__increase {
    width: 28PX;
    height: 28PX;
    border-radius: 0PX;
  }

  .el-input__inner, .el-input__wrapper {
    height: 30PX !important;
    border-radius: 0 !important;
  }

  .el-icon {
    font-size: 14PX;
  }

}

:deep(.el-input) {
  height: 30PX;

  .el-input__inner, .el-input__wrapper {
    height: 30PX !important;
    border-radius: 12PX;
    box-shadow: none;
    overflow: hidden;
  }


}
:deep(.sku) {}

:deep(.el-textarea ) {
  height: 60PX !important;

  .el-textarea__inner {
    height: 60PX !important;
    font-size: 10PX;
  }

}


:deep(.el-select) {
  height: 30PX !important;

  .el-select__selected-item, .el-input__inner, .el-select__wrapper {
    height: 30PX !important;


  }

  .el-select__placeholder {
    display: flex !important;
    align-content: center;
    align-items: center;
  }

}

:deep(.el-form-item) {
  margin-bottom: 0PX;
  margin-top: 15PX;
}


</style>
